/* eslint-disable no-console,no-undef,no-unused-vars,no-debugger */
import Vue from 'vue'
import App from './App.vue'
import router from './router/index'
import store from './store/index'

import axios from "axios";
import ApiUrl from "./store/ApiUrl";

/*import Mint from 'mint-ui';
import 'mint-ui/lib/style.css'*/

axios.defaults.baseURL = "http://api.51self-service.cn";
// axios.defaults.baseURL = "http://localhost:9404";
axios.defaults.headers.openid = store.state.openid;

async function get(url, params) {
    console.log("-----before get----");
    console.log(url);
    if (url !== ApiUrl.GET_USER_OPENID && !store.state.doctor) {
        console.log("-----throw 500 get----");
        setTimeout(function () {
            console.log("------------axios get::goToAuth-----------");
            router.push({name: 'authentication'});
        }, 500);
        throw 500;
    } else {
        console.log("-----after get----");
        return await axios.get(url, params)
    }
}

async function post(url, params) {
    if (url !== ApiUrl.POST_DOCTOR_APPLY && !store.state.doctor) {
        console.log("-----before post----");
        setTimeout(function () {
            console.log("------------axios post::goToAuth-----------");
            router.push({name: 'authentication'});
        }, 500);
        throw 500;
    } else {
        console.log("-----after post----");
        return await axios.post(url, params);
    }
}

async function put(url, params) {
    console.log("-----before put----");
    return await axios.put(url, params);
}

async function del(url, params) {
    console.log("-----before del----");
    return await axios.delete(url, params);
}

async function patch(url, params) {
    console.log("-----before patch----");
    return await axios.patch(url, params);
}

axios.GET = get;
axios.POST = post;
axios.PUT = put;
axios.DELETE = del;
axios.PATCH = patch;

Vue.prototype.API = axios;
Vue.prototype.ApiUrl = ApiUrl;

import {
    Dialog, SearchBar, Tabbar, Swiper, Tab, TabPanel, Navbar, Cell, Calendar, Switch,Radio,
    ActionSheet, TextInput, Button, DatePicker, Col, Row, Toast, Picker, Stepper, NoticeBar,
    ButtonGroup,Price
} from '@nutui/nutui';

Dialog.install(Vue);
SearchBar.install(Vue);
Tabbar.install(Vue);
Swiper.install(Vue);
Tab.install(Vue);
TabPanel.install(Vue);
Navbar.install(Vue);
Cell.install(Vue);
Calendar.install(Vue);
Switch.install(Vue);
Radio.install(Vue);
ActionSheet.install(Vue);
TextInput.install(Vue);
Button.install(Vue);
DatePicker.install(Vue);
NoticeBar.install(Vue);
Col.install(Vue);
Row.install(Vue);
Toast.install(Vue);
Picker.install(Vue);
Stepper.install(Vue);
ButtonGroup.install(Vue);
Price.install(Vue);

//数组增强功能，删除数组指定下标
Array.prototype.del = function (dx) {
    if (isNaN(dx) || dx > this.length) {
        return false;
    }
    this.splice(dx, 1);
}

Vue.config.productionTip = false;

let vm = new Vue({
    router,
    store,
    render: h => h(App),
    mounted() {
        console.log("-------加载组件完成了------");
    },
    created() {
        console.log("init project begin");
        console.log(ApiUrl.WECHAT);
        console.log(store.state);
        console.log(window.localStorage.getItem("openid"));
        if (window.localStorage.getItem("openid")) {
            store.state.openid = window.localStorage.getItem("openid");
        }
        if (window.localStorage.getItem("orderNo")) {
            store.state.orderNo = window.localStorage.getItem("orderNo");
        }
        window.localStorage.removeItem("openid");
        window.localStorage.removeItem("orderNo");

        axios.defaults.headers.openid = store.state.openid;

        let obj = this.qsParse(window.location.href);
        this.getUserInfo(obj.orderNo);

        console.log("init project end");
        if (!store.state.openid) {
            window.location.href = "http://api.51self-service.cn/wx/authorize?returnUrl=" + encodeURIComponent(window.location.href);
        }

        this.initWechat();

    },
    methods: {
        initWechat: function () {
            axios.get(ApiUrl.GET_WECHAT, {
                params: {
                    openid: store.state.openid,
                    url: window.location.href.split("#")[0]
                }
            }).then(({data}) => {
                console.log("wxjssdk------", data);
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: data.data.appId, // 必填，公众号的唯一标识
                    timestamp: data.data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: data.data.nonceStr, // 必填，生成签名的随机串
                    signature: data.data.signature,// 必填，签名
                    jsApiList: [
                        "chooseImage",
                        "previewImage",
                        "uploadImage",
                        "downloadImage",
                        "updateAppMessageShareData",
                        "onMenuShareAppMessage",
                        "chooseWXPay",
                        "onMenuShareTimeline",
                        "onMenuShareQQ",
                        "hideAllNonBaseMenuItem"
                    ] // 必填，需要使用的JS接口列表
                });
                wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                    //隐藏所有非基础按钮接口
                    wx.hideAllNonBaseMenuItem();
                });
                wx.error(function (res) {
                    // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，
                    // 也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                    /*vm.$toast.text("微信初始化失败:" + JSON.stringify(res));
                    vm.initWechat();*/
                });
            }).catch(err => {
                console.log(err);
                //请求异常，重试
                vm.initWechat();
            });
        },
        getUserInfo: function (orderNo) {
            axios.get(this.ApiUrl.GET_USER_OPENID, {
                params: {
                    openid: this.$store.state.openid
                }
            }).then(({data}) => {
                if (data.code === 1200) {
                    this.$store.state.inited = true;
                    if (data.data.type === "doctor") {

                        document.title = data.data.doctorInfo.doctorName + "online门诊";

                        this.$store.state.doctor = data.data.doctorInfo;
                        this.$store.state.apply = data.data.applyInfo;
                        let url = window.location.href;
                        if (!url.includes("about")
                            && !url.includes("receive")
                            && !url.includes("presonal")) {
                            /*this.goToPay(orderNo);
                        }else{*/
                            this.$router.push({name: 'home'});
                        }
                    } else if (data.data.type === "apply") {
                        this.$store.state.apply = data.data.applyInfo;
                    }
                }
            }).catch(err => {
                console.log("getUserInfoByOpenid::err------", err);
                this.getUserInfo();
            });
        },
        goToAuth: function () {
            this.$router.push({name: 'authentication'});
        },
        goToPay: function (orderNo) {
            this.$router.push({name: 'costClear', params: {orderNo: orderNo}});
        },
        qsParse: function (url) {
            if (!url.includes("?")) {
                return {};
            }
            let arr1 = url.split("?");
            let params = arr1[1].split("&");
            let obj = {};//声明对象
            for (let i = 0; i < params.length; i++) {
                let param = params[i].split("=");
                obj[param[0]] = param[1];//为对象赋值
            }
            return obj;
        },
    }
}).$mount('#app');

window.vm = vm;
